#include <iostream>
#include <thread>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void handleReceive(int serverSocket) {
    char buffer[1024];
    while (true) {
        memset(buffer, 0, sizeof(buffer));
        int bytesReceived = recv(serverSocket, buffer, sizeof(buffer) - 1, 0);
        
        if (bytesReceived <= 0) {
            std::cout << "服务器已断开连接。" << std::endl;
            break;
        }
        
        std::cout << "服务器说: " << buffer << std::endl;
    }
    close(serverSocket);
}

void handleSend(int serverSocket) {
    std::string message;
    while (true) {
        std::getline(std::cin, message);
        if (send(serverSocket, message.c_str(), message.length(), 0) < 0) {
            std::cout << "连接已断开，无法发送消息。" << std::endl;
            break;
        }
    }
    close(serverSocket);
}

int main() {
    // 创建客户端套接字
    int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSocket < 0) {
        std::cerr << "创建套接字失败" << std::endl;
        return 1;
    }
    
    // 设置服务器地址
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(12345);
    
    // 将IP地址从文本转换为二进制形式
    if (inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr) <= 0) {
        std::cerr << "无效的IP地址" << std::endl;
        close(clientSocket);
        return 1;
    }
    
    // 连接到服务器
    std::cout << "正在连接到服务器..." << std::endl;
    if (connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        std::cerr << "连接服务器失败" << std::endl;
        close(clientSocket);
        return 1;
    }
    
    std::cout << "已连接到服务器。" << std::endl;
    
    // 创建收发线程
    std::thread receiveThread(handleReceive, clientSocket);
    std::thread sendThread(handleSend, clientSocket);
    
    // 等待线程结束
    receiveThread.join();
    sendThread.join();
    
    // 关闭套接字
    close(clientSocket);
    std::cout << "客户端已关闭。" << std::endl;
    
    return 0;
}